import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from "../views/Login";
import Head from "../views/Head";
import Index from "../views/Index";
import Main from "../views/Main";
import Edit from "../views/Edit";
import Datepicker from "../views/Datepicker";
import Fill from "../views/Fill";

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/index',
        meta: {
            requireAuth: true
        }
    },
    {
        path: '/login',
        name: '登录页面',
        component: Login
    },
    {
        path: '/datepicker',
        name: 'Datepicker',
        component: Datepicker,
        meta: {
            requireAuth: true
        }
    },
    {
        path: '/head',
        name: 'Head',
        component: Head,
        meta: {
            requireAuth: true
        },
        children: [
            {
                path: '/main',
                name: 'Main',
                component: Main,
                meta: {
                    requireAuth: true
                },
                children: [
                    {
                        path: '/index',
                        redirect: '/index/2/0',
                        meta: {
                            requireAuth: true
                        }
                    },
                    {
                        path: '/index/:id/:isDelete',
                        name: 'Index',
                        component: Index,
                        meta: {
                            requireAuth: true
                        }
                    }
                ]
            },
            {
                path: '/edit/:id',
                name: 'Edit',
                component: Edit,
                meta: {
                    requireAuth: true
                }
            },
            {
                path: '/fill/:id',
                name: 'Fill',
                component: Fill,
                meta: {
                    requireAuth: true
                }
            }
        ]
    }
]

const router = new VueRouter({
    mode: 'history',
    routes
})

export default router

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
        if (sessionStorage.getItem("token") == 'true') { // 判断本地是否存在token
            next()
        } else {
            // 未登录,跳转到登陆页面
            next({
                path: '/login'
            })
        }
    } else {
        if (sessionStorage.getItem("token") == 'true') {
            next('/index/2/0');
        } else {
            next();
        }
    }
});
